import time
from hashlib import md5
import requests
import config

url = "https://fanyi-api.baidu.com/api/trans/vip/translate"
headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
}


def do_post(purl, pheader, pdata):
    time.sleep(1)
    text = requests.post(purl, data=pdata, headers=pheader)
    son = text.json()
    try:
        trans_result = son['trans_result']
    except Exception as e:
        return 'err'
    re = ''
    for txt in trans_result:
        re += txt['dst'] + '\n'
    return re


def explain(text):
    global url, headers
    new_md5 = md5()
    q = text.replace("\"", "`").replace("'", "`").replace("=", "-")
    temp = config.getAppid() + q + config.getSalt() + config.getKey()
    new_md5.update(temp.encode(encoding='utf-8'))
    sign = new_md5.hexdigest()
    data = {
        'q': q,
        'from': 'en',
        'to': 'zh',
        'appid': config.getAppid(),
        'salt': config.getSalt(),
        'sign': sign
    }
    return do_post(url, headers, data)


def run(text):
    for i in range(1, 5):
        re = explain(text)
        if len(re) >= 10:
            return re.replace("\"", "`").replace("'", "`")
    return "err"
